<?php

namespace App\Admin\Controllers\Dhe;

use App\Admin\Actions\Grid\Batch\SwtDheGood\SyncGoods;
use App\Admin\Actions\Grid\Tools\SwtDheGood\GoodSyncData;
use App\Admin\Actions\RestoreActions;
use App\Admin\Repositories\SwtDheGood;
use App\Models\SwtGood;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;

class SwtDheGoodController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        return Grid::make(SwtDheGood::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');

            $grid->column('id')->sortable();
            $grid->column('goods_id','商品库ID') -> display( function ($value) {
                return $value ? : '<span class="text-danger">暂未同步</span>';
            });
            $grid->column('sku_id');
            $grid->column('goods_name');
            $grid->column('goods_package');
            $grid->column('weight');
            $grid->column('cost_price') -> display( function ($value) {
                return bcdiv($value, 1000, 3);
            });
            $grid->column('sell_price') -> display( function ($value) {
                return bcdiv($value, 100, 2);
            });
            $grid->column('created_at');
            $grid->column('updated_at');


            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new RestoreActions(\App\Models\SwtDheGood::class));
                }

                if(!$this->goods_id) {
                    $actions->disableDelete(false);
                }
            });


            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('sku_id');
                $filter->like('goods_name');
                $filter->scope('trashed', '回收站')->onlyTrashed();

            });

            $grid->disableRowSelector(false);

            $grid->rowSelector()->titleColumn('id');

            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                $batch->add(new SyncGoods());
                $batch->disableDelete();
            });

            $grid->quickSearch('sku_id');

            $grid->tools(new GoodSyncData());

        });
    }



    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new SwtDheGood(), function (Form $form) {
            $form->display('id');
            $form->display('goods_id');

            if($form->isEditing()) {
                $goods_id = $form -> model() -> goods_id;
                if($goods_id) {
                    SwtGood::where('id', $goods_id) -> update(['goods_name' => $form -> input('with_name')]);
                }
            }
        });
    }
}
